package cn.com.callback

import groovy.json.*;
import groovy.swing.impl.DefaultAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.RequestDispatcher;
import cn.com.elite.EliteBean;
import java.security.MessageDigest;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wisdge.dataservice.Result;
import java.util.Map;
import java.util.Date;
import java.util.HashMap;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import cn.com.elite.Util;

/**
 *
 * @Title: apiReturnVisit
 * @Description:深圳水务系统工单数据回访接口---内部动态页面调用，外部第三方接口调用
 * @author: chieh
 * @date 2019-12-17 02:28:00
 *
 */

public class apiReturnVisit implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(apiReturnVisit.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");

		String getMethod = request.getMethod();
		log.debug("getMethod:" + getMethod);

		String inData = "";
		String outData = "";
		String dataSourceID = "dataSource";

		BufferedReader iny = null;
		if (getMethod.equals("GET")) {
			inData = request.getParameter("data");
			log.debug("原始Get请求参数:" + inData);
		} else {
			InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
			iny = new BufferedReader(reader);
			String line;
			while ((line = iny.readLine()) != null) {
				inData += line;
			}
			log.debug("原始Post请求参数:" + inData);
		}

		try {
			// 调用处理信息
			JSONObject inObject = new JSONObject(inData);
			log.debug("处理前的Json：" + inObject.toString());

			String sys_source = GetJV(inObject, "sys_source");
			String sys_flag = GetJV(inObject, "sys_flag");
			String arr_data = GetJV(inObject, "data");

			log.debug("解析信息- sys_source：" + sys_source+' sys_flag：'+sys_flag+' arr_data：'+arr_data);

			if(sys_source == "CRM" && (sys_flag == "JT" || sys_flag == "GM" || sys_flag == "BA")) {
				if(sys_flag == "JT") {
					outData = postJTVisit(eliteBean, sys_source, sys_flag, arr_data, dataSourceID);
				}
				else if(sys_flag == "GM"){
					outData = postGMVisit(eliteBean, sys_source, sys_flag, arr_data, dataSourceID);
				}
				else if(sys_flag == "BA") {
					outData = postBAVisit(eliteBean, sys_source, sys_flag, arr_data, dataSourceID);

				}else {
					outData ="{\"resultcode\":\"0\",\"resultmessage\":\"处理失败,不支持的sys_flag标识\",\"data\":[]}"
				}
			}else {

				outData = returnVisit(eliteBean, sys_source, sys_flag, arr_data, dataSourceID);

			}

		} catch (Exception e) {
			log.error("接口处理异常" + e.getMessage());
			// 失败返回
			outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):2\",\"data\":[]}";

		}

		log.debug("名单接入处理完成返回结果:" + outData);

		return outData;
	}

	// 动态页面通知调用通知UCIS回访结果
	public static String postJTVisit(EliteBean eliteBean, String sys_source, String sys_flag, String arr_data, String dataSourceID) {
		long startTime = System.currentTimeMillis();

		String reJson = null;
		try {

			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":宝安工单回访成功!}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":宝安工单回访失败!}";
		}

		return reJson;
	}

	// 动态页面通知调用通知光明回访结果
	public static String postGMVisit(EliteBean eliteBean, String sys_source, String sys_flag, String arr_data, String dataSourceID) {
		long startTime = System.currentTimeMillis();

		String reJson = null;
		try {

			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":宝安工单回访成功!}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":宝安工单回访失败!}";
		}

		return reJson;
	}

	// 动态页面通知调用通知宝安回访结果
	public static String postBAVisit(EliteBean eliteBean, String sys_source, String sys_flag, String arr_data, String dataSourceID) {
		long startTime = System.currentTimeMillis();
		JSONArray arrJsonArray;
		Map<String, String> dealMap = new HashMap<String, String>();
		JSONArray resArray = new JSONArray();
		String reJson = null;
		try {
			arrJsonArray = new JSONArray(arr_data);

			int arrInt = arrJsonArray.length();
			log.debug("接入List数量:" + arrInt);

			for (int i = 0; i < arrInt; i++) {
				JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

				//解析接口推送的回访结果信息
				String id = GetJV(arrCustJson, "id");

				def procedure="{call BAGDInformation(?,?,?,?)}";
				def temp=new String[3];
				temp[0] = "BA";
				temp[1] = id;
				temp[2] = "5";//回访
				def dealResult = eliteBean.executeWithReturn(procedure,temp,"dataSource");
				log.debug("调用通知宝安回访存储过程结果result:" + dealResult);

				dealMap.put(id, dealResult);
			}

			// 将每条处理结果转换为JSONArray
			int j = 0;
			for (Map.Entry<String, String> m : dealMap.entrySet()) {
				JSONObject resObject = new JSONObject();
				resObject.put("id", m.getKey());
				resObject.put("code", m.getValue());
				resArray.put(j, resObject);
				j++;
			}

			log.debug(resArray.toString());

			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
		}

		return reJson;
	}

	// 第三方系统通知CRM回访已经完成处理
	public static String returnVisit(EliteBean eliteBean, String sys_source, String sys_flag, String arr_data, String dataSourceID) {
		long startTime = System.currentTimeMillis();
		JSONArray arrJsonArray;
		Map<String, String> dealMap = new HashMap<String, String>();
		Map<String, String> dealMsgMap = new HashMap<String, String>();
		JSONArray resArray = new JSONArray();
		String reJson = null;
		try {
			arrJsonArray = new JSONArray(arr_data);

			int arrInt = arrJsonArray.length();
			log.debug("接入List数量:" + arrInt);

			for (int i = 0; i < arrInt; i++) {
				JSONObject arrCustJson = arrJsonArray.getJSONObject(i);

				//解析接口推送的回访结果信息
				String id = GetJV(arrCustJson, "id");
				String userreflect = GetJV(arrCustJson, "userreflect");
				String serviceattitude = GetJV(arrCustJson, "serviceattitude");
				String quality = GetJV(arrCustJson, "quality");
				String returnpeople = GetJV(arrCustJson, "returnpeople");
				String returnname = GetJV(arrCustJson, "returnname");
				String feedbacktime = GetJV(arrCustJson, "feedbacktime");
				String satisfaction = GetJV(arrCustJson, "satisfaction");
				String empattire = GetJV(arrCustJson, "empattire");
				String feedback = GetJV(arrCustJson, "feedback");

				//查询现有当前工单编号是否存在现有工单
				def getSelectSQL = eliteBean.chaxun_sql("select top 1 Relation_ID from TABCswgdmerge where workorderid = '" + id + "'", dataSourceID);
				log.debug("查询当前同步的工单是否已经存在 SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());

				//获取当前工单编号对应的CRM唯一工单Guid Relation_ID
				String old_Relation_ID = null;
				if(getSelectSQL.size() > 0) {
					old_Relation_ID = getSelectSQL.get(0).get("Relation_ID");
				}else{
					old_Relation_ID = null;
				}

				log.debug("当前处理结果变更的工单在CRM系统唯一Relation_ID:" + old_Relation_ID);

				String dealResult = "";
				String dealMessage = "";
				if(old_Relation_ID != null && old_Relation_ID.length() > 0) {

					if(isNull(id)||isNull(userreflect)||isNull(serviceattitude)||isNull(quality)||isNull(returnpeople)||isNull(returnname)||isNull(feedbacktime)||isNull(satisfaction)||isNull(empattire)||isNull(feedback))
					{
						dealResult = "0";
						dealMessage = isNullMSG("id", id) + isNullMSG("userreflect", userreflect) + isNullMSG("serviceattitude", serviceattitude) + isNullMSG("quality", quality) + isNullMSG("returnpeople", returnpeople) + isNullMSG("returnname", returnname) + isNullMSG("feedbacktime", feedbacktime)+ isNullMSG("satisfaction", satisfaction) + isNullMSG("empattire", empattire) + isNullMSG("feedback", feedback);

					}else {
						try {
							//更新工单回访处理结果
							String[] data=new String[2];
							data[0]  = "Insert Into Tabcswgdmerge_His Select Newid(),* From Tabcswgdmerge Where Relation_Id = '" + old_Relation_ID + "'";
							data[1]  = "Update Tabcswgdmerge Set Userreflect = '" + userreflect + "', Serviceattitude = '" + serviceattitude + "', Quality = '" + quality + "', Returnpeople = '" + returnpeople + "', Returnname = '" + returnname + "', Feedbacktime = '" + feedbacktime + "', Satisfaction = '" + satisfaction + "', Empattire = '" + empattire + "', Feedback = '" + feedback + "' Where Relation_Id = '" + old_Relation_ID + "'";

							log.debug("更新工单回访处理结果SQL:" + data.toString());
							def dataresult = eliteBean.updateBatch(data, dataSourceID);
							log.debug("更新工单回访处理结果SQL结果:" + dataresult.toString());

							dealResult = "1";

						} catch (Exception e) {
							dealResult = "0";
							dealMessage = "更新工单回访处理结果SQL异常";
							log.error(dealMessage + ":" + e.getMessage());
						}
					}

				}else {
					dealResult = "0";
					dealMessage = "当前回访结果变更的工单在CRM系统不存在ID";
					log.warn(dealMessage + ":" + id);
				}

				dealMap.put(id, dealResult);
				dealMsgMap.put(id, dealMessage);
			}

			// 将每条处理结果转换为JSONArray
			int j = 0;
			for (Map.Entry<String, String> m : dealMap.entrySet()) {
				JSONObject resObject = new JSONObject();
				resObject.put("id", m.getKey());
				resObject.put("code", m.getValue());
				resObject.put("message", dealMsgMap.get(m.getKey()).toString());
				resArray.put(j, resObject);
				j++;
			}

			log.debug(resArray.toString());

			long endTime = System.currentTimeMillis();
			// 包装拼接返回JSONObject
			reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"处理完成、调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";

		} catch (JSONException e) {
			long endTime = System.currentTimeMillis();
			reJson = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + "),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
		}

		return reJson;

	}

	// 解析Json值
	public static String GetJV(JSONObject inJson, String getKey) {
		String Rev_Value = null;
		try {
			Rev_Value = inJson.getString(getKey);
		} catch (Exception e) {
			try {
				Rev_Value = String.valueOf(inJson.getInt(getKey));
			} catch (Exception e1) {
				try {
					Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
				} catch (Exception e2) {
					try {
						Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
					} catch (Exception e3) {
						Rev_Value = "";
					}
				}
			}
		} finally {
			if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
				Rev_Value = "";
			} else {
			}
		}
		return Rev_Value;
	}

	// 非空校验isNull
	public static boolean isNull(String value) {

		boolean reFlag = true;
		if (value == "" || value.length() <= 0) {
			reFlag = true;
		} else {
			reFlag = false;
		}
		log.debug(reFlag);
		return reFlag;
	}

	// 非空校验isNullMSG
	public static String isNullMSG(String key, String value) {

		String reResult = "";
		if (value == "" || value.length() <= 0) {
			reResult = key + "必填字段;";
		}
		return reResult;
	}

}
